﻿using System;
using System.Web;
using INHollandair.Core.Models;
using INHollandair.Core.Services;

namespace INHollandair.Shop
{
    public partial class ConfirmOrder : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            pnl_OrderSucces.Visible = false;

            string orderUrl = (Request.QueryString["OrderUrl"] != null) ? Server.HtmlEncode(Request.QueryString["OrderUrl"]) : String.Empty;

            if (Session["OrderSuccesful"] != null)
            {
                pnl_OrderSucces.Visible = true;
            }
            else if (!orderUrl.Equals(string.Empty))
            {
                OrderService svc = new OrderService();
                Order url = svc.GetOrderByUrl(orderUrl);

                if (url != null)
                {
                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        //Retrieve and update order
                        Order newOrder = svc.GetOrderByUrl(orderUrl);
                        newOrder.confirmed = true;
                        svc.UpdateOrder(newOrder);

                        //Retrieve product
                        ProductService productService = new ProductService();
                        Product product = productService.GetProductById(newOrder.ProductID);

                        //Retrieve and update user
                        UserService userService = new UserService();
                    
                        User newUser = userService.GetUserByName(HttpContext.Current.User.Identity.Name);
                        newUser.Points -= Convert.ToInt32(product.Price);
                        userService.UpdateUser(newUser);

                        Session["OrderSuccesful"] = true;
                        Response.Redirect("~/Shop/ConfirmOrder.aspx");
                    }
                    else
                    {
                        Response.Redirect(String.Format("~/Account/Login.aspx?ReturnUrl=%2fShop%2fConfirmOrder.aspx?OrderUrl={0}", url.OrderURL));
                    }
                }
                else
                {
                    Response.Redirect("~/Default.aspx"); //gebruiker zit te prutsen met strings
                }
            }
            else
            {
                Response.Redirect("~/Default.aspx"); //gebruiker heeft hier niks te zoeken
            }
        }
    }
}